package org.example.lost.controller;

import ch.qos.logback.core.util.FileUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.example.domain.Result;
import org.example.lost.service.ImageService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ClassUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Objects;
import java.util.Vector;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

/**
 * 图片上传模块
 * 1、图片上传，图片上传后，可以通过http://localhost:8661/images/图片名 访问到该图片
 * 2、撤销图片
 * @Author hxy
 * @Date 2021/3/25 8:45
 * @Version 1.0
 */
@RestController
@RequestMapping("/core")
@Api(tags = "图片处理")
//@CrossOrigin(allowCredentials = "true",allowedHeaders="*")
public class ImageController {
    private static final Logger LOGGER= LoggerFactory.getLogger(ImageController.class);

    @Autowired
    ImageService imageService;

    @PostMapping("/image")
    @ApiOperation("图片上传")
    public Result<String> upload(@RequestParam("file") MultipartFile image){
        if(!image.isEmpty()){
            /** 获取项目静态资源位置*/
            String staticPath = ImageController.class.getResource("/").getPath()+"static/images";
            String filename = image.getOriginalFilename();
            int index=filename.contains(".")?filename.lastIndexOf("."):-1;
            String type="",imageName="";
            if(index != -1){
                type=filename.substring(index+1,filename.length());
                imageName=filename.substring(0,index);
            }
            if(type.equals("jpg")){
                try{
                    File imageFile=new File(staticPath,filename);
                    boolean newFile = imageFile.createNewFile();
                    if(newFile){
                        image.transferTo(imageFile);
                    }
                    return Result.success("images/"+filename);
                }catch (IOException ioe){
                    return Result.fail("上传文件错误！");
                }
            }
            return Result.fail("图片格式不符合");
        }
        return Result.fail("请选择文件");
    }


    @DeleteMapping("/image/{imageName}")
    @ApiOperation("删除图片")
    public Result<String> delete(@PathVariable("imageName") @ApiParam(name = "imageName",value = "图片名字") String imageName){
        String staticPath = ImageController.class.getResource("/").getPath()+"static/images";
        File file=new File(staticPath,imageName);
        if(file.exists()){
            file.delete();
        }
        return Result.fail("图片删除成功");

    }

}
